
let jwtUtil = require('../utils/jwtUtil')
const redisUtil = require('../utils/redisUtil')
const tools =require('../utils/tools')
const mymsql =require('../utils/mysqlUtil')
//注册
let regist = async (req,res) => {
    let body = req.body
    let name = body.name
    let account=body.account
    let pwd = body.pwd

    if ( !name|| !pwd|| !account ) {
        tools.error(res,"关键字缺失")
        return
    }

    let username =await mymsql.exec("select * from user where name= ? ",mymsql.formatParams(name))

    if (username.length !=0) {
        tools.error(res,"用户名存在")
        return
    }else{
        await mymsql.exec("INSERT INTO USER (id, name ,account,pwd) values (?,?,?,?)",mymsql.formatParams(tools.newId(),name,account,pwd))
        res.send("注册成功")
    }



    // global.username = name
    // global.userpwd = pwd
    // req.session.username =name
    // req.session.userpwd =pwd
    // console.log(`会话ID: ${req.sessionID}`)
}
//登录
let login =async(req,res) => {
    let query = req.query
    let name = query.name
    let pwd = query.pwd
    let captcha=query.captcha

    let user =await mymsql.exec("SELECT * from user  WHERE name = ? and pwd = ?",mymsql.formatParams(name,pwd))
    console.log(user)
    console.log(user[0],name)

    if (user.length !=0  ){
        if (captcha !=await redisUtil.get("captcha")) {
            console.log(captcha,await redisUtil.get("captcha"))
            tools.error(res,"验证码错误")
        }else {
            res.send("登录成功")
            return
        }
    }else {
        tools.error(res,"用户名或密码错误")
    }
    redisUtil.set("user",JSON.stringify(user))

    // if (name == username && pwd == userpwd){
    //     // console.log(`当前全局用户名 ${req.session.username},当前全局密码 ${req.session.userpwd}`)
    //     let user ={id: "1",name:"weihao"}
    //     // res.send("登录成功")
    //     await redisUtil.set(user.id,user,6000)
    //     res.send(jwtUtil.sign({id:user.id},global.globalKey,6000))
    // }else{
    //     throw new Error("用户名或密码错误")
    // }

}

//获取用户信息
let getUserInfo =async (req,res) => {
    let header = req.headers
    let token = header.token
    let user =await redisUtil.get("user")


    res.send({
        // name :req.query.name,
        // class : "xunke",
        token:token,
        user:user
    })
}

//创建cookie
let getCookieMsg = (req,res) => {
    //1. 创建cookie
    res.cookie("Jason","123")
    //2. 把cookie数据发送给客户端
    res.send({
        cookieKey:"Jason"
    })
}

let captchaValid =async (req,res) =>{
    let captcha = req.query.captcha
    console.log( await redisUtil.get(captcha),captcha)
    let eq =await redisUtil.get('captcha' ) == captcha
    if (eq){
        res.send("验证码正确")
    } else{
        throw new Error("验证失败")
    }
}

module.exports={regist,login,getUserInfo,getCookieMsg,captchaValid}